package com.yazdee;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.yazdee.config.ConfigValues;
import com.yazdee.productdetail.ProductDetail;
import com.yazdee.searchresult.SearchResultHandler;
import com.yazdee.searchresult.SearchResultRow;

public class SearchResults extends ListActivity {
	private boolean catgBrowse=false;
	private boolean search=false;
	private String keyword;
	private SearchAdapter mAdapter;
	private ArrayList items;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.searchresult);
		/*catgBrowse = savedInstanceState != null ? savedInstanceState.getBoolean("Browse"): null;
		search=savedInstanceState != null ? savedInstanceState.getBoolean("Search"): null;*/
		
		if (catgBrowse == false && search==false) {
		    Bundle extras = getIntent().getExtras();
		    catgBrowse = extras != null ? extras.getBoolean("Browse"): null;
		    search=extras != null ? extras.getBoolean("Search"): null;
		}
		
		populateRows();
	}
	
	private List getSearchResultsRows(String text,boolean doSearch){
		   
				SearchResultHandler elementHandler;
				try {
					URL url;
					if(doSearch) {
						url = new URL(ConfigValues.SearchProductURL);
					}
					else 
					url = new URL(ConfigValues.CatalogBrowseURL);
					
					SAXParserFactory spf = SAXParserFactory.newInstance();
					SAXParser sp = spf.newSAXParser();

					XMLReader xr = sp.getXMLReader();

					elementHandler = new SearchResultHandler();
					xr.setContentHandler(elementHandler);
					
					xr.parse(new InputSource(url.openStream()));
					return(elementHandler.getSearchResultRows());
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (FactoryConfigurationError e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return null;	
	   }		
		   
	@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	super.onListItemClick(l, v, position, id);
    	
    	Intent i = new Intent(this, ProductDetail.class);
    	i.putExtra("type", "");
    	
    	startActivity(i);
    }
	
	private class SearchAdapter extends ArrayAdapter{
		private ArrayList<SearchResultRow> items;
		
		public SearchAdapter(Context context, int textViewResourceId, ArrayList<SearchResultRow> items) {
            super(context, textViewResourceId, items);
            this.items = items;
		}
		
		@Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.searchresultrows, null);
                }
                SearchResultRow o = items.get(position);
                if (o != null) {
                        TextView tt = (TextView) v.findViewById(R.id.productName);
                       ImageView imgSrch=(ImageView)v.findViewById(R.id.searchPageImg);
                        if (tt != null) {
                              tt.setText(o.getName());  
                              Drawable image = ImageOperations(SearchResults.this,o.getImageURL(),"");
                              imgSrch.setImageDrawable(image);
                        }
                }
                return v;
        }
	}
	

private void populateRows() {
    if (catgBrowse==true) {
    	items=(ArrayList)getSearchResultsRows("",false);
		mAdapter=new SearchAdapter(this,R.layout.searchresultrows,items);
		setListAdapter(mAdapter);
	} else if(search==true){
		items=(ArrayList)getSearchResultsRows("",true);
		mAdapter=new SearchAdapter(this,R.layout.searchresultrows,items);
		setListAdapter(mAdapter);
	}
}

@Override
protected void onPause() {
	super.onPause();
    saveState();
}

@Override
protected void onResume() {
	super.onResume();
    populateRows();

}

@Override
protected void onSaveInstanceState(Bundle outState) {
	  super.onSaveInstanceState(outState);
      outState.putBoolean("Browse", catgBrowse);
      outState.putBoolean("Search", search);
}

private void saveState() {
 // Nothing to do    
}

private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
	try {
		InputStream is = (InputStream) this.fetch(url);
		Drawable d = Drawable.createFromStream(is, "src");
		return d;
	} catch (MalformedURLException e) {
		e.printStackTrace();
		return null;
	} catch (IOException e) {
		e.printStackTrace();
		return null;
	}
}

public Object fetch(String address) throws MalformedURLException,IOException {
	URL url = new URL(address);
	Object content = url.getContent();
	return content;
}
}